package com.collectplus.express.sender;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.collectplus.express.BaseFragment;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.model.SenderBean;
import com.shouhuobao.bhi.receiver.ReceiverHistoryAdapter;
import com.shouhuobao.bhi.receiver.ReceiverHistoryFragment;

import droid.frame.activity.HandlerMgr;
import droid.frame.app.Callback;

/**
 * 寄件人列表
 *
 * @author coffee<br>
 * 2016-11-29下午5:53:17
 */
public class SenderHistoryFragment extends BaseFragment implements OnClickListener {

    private ListView mListView;
    private ReceiverHistoryAdapter mAdapter;

    private int mPageNum = 1;

    /**
     * 选中的联系人Id,
     */
    private StringBuilder selectIds = new StringBuilder();
    // private DeletePopupWindow mDdeletePopwin;// 删除框
    private ReceiverBean clickItem;

    private int position;// 当前操作(长按)的item

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showLoadingDialog(null);
        //addType:地址类型1：收件，2：寄件
        AppHttp.getInstance().senderList(mPageNum,2);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.receiver_history);
        super.findViewById();

        mListView = (ListView) findViewById(R.id.listview);
        // mListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        // @Override
        // public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        // menu.add(0, 1, 0, "删除寄件人");
        // }
        // });

        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
//		 clickItem = mAdapter.getItem(position);
//		 mListView.showContextMenu();

                SenderHistoryFragment.this.position = position;
                final ReceiverBean receiver = mAdapter.getItem(position);
                DialogMgr.deleteReceiverHistory(getActivityContext(), receiver, new Callback() {
                    @Override
                    public void onDialogDismiss() {
                        showLoadingDialog(null);
                        AppHttp.getInstance().receiverDeleteFromHistory(receiver.getId(), position);
                    }
                });
                return true;
            }
        });

		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAdapter.setCheck(position);
				clickItem = (ReceiverBean) parent.getItemAtPosition(position);
				onCheck(clickItem);
			}
		});
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:// 删除
                showLoadingDialog(null);
                // AppHttp.getInstance().receiverDeleteFromHistory(clickItem.getId());
                break;
        }
        return super.onContextItemSelected(item);
    }

    private void onCheck(ReceiverBean item) {
        selectIds.setLength(0);
        selectIds.append(item.getId());// 收件人ID
        selectIds.append(",");

        if (TextUtils.isEmpty(selectIds.toString())) {
            showToast("请选择联系人");
            return;
        }
        ReceiverBean cacheReceiver = AppCache.getParcelNew();

        SenderBean sender = new SenderBean();
        sender.setId(item.getId());
        sender.setName(item.getName());
        sender.setPhone(item.getPhone());
        sender.setProvince(item.getProvince());
        sender.setCity(item.getCity());
        sender.setDistrict(item.getDistrict());
        sender.setAddress(item.getAddress());
        sender.setProvinceId(item.getProvinceId());
        sender.setCityId(item.getCityId());
        sender.setDistrictId(item.getDistrictId());
        cacheReceiver.setSender(sender);
        //
        Intent data = new Intent();
        getActivityContext().setResult(Activity.RESULT_OK, data);
        getActivityContext().finish();
    }

    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            // 获取寄件人列表
            case MsgID.senderList:
                cancelLoadingDialog();
                final AppResult<ReceiverBean> appResult = JSON.parseList(msg.obj, ReceiverBean.class);
                //
                if (appResult.isSuccess()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter = new ReceiverHistoryAdapter(getActivityContext(), appResult.getResultList(), SenderHistoryFragment.this);
                            mListView.setAdapter(mAdapter);
                        }
                    });
                }
                return true;
            // 删除历史寄件人
            case MsgID.receiver_Delete_from_history:
                cancelLoadingDialog();
                AppResult<?> deleteResult = JSON.parser(msg.obj);
                switch (deleteResult.getStatus()) {
                    case 1:
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                int removedPosition = msg.arg1;

                                // 如果删除的是已经选中的(注意msg.arg1 即可能是List的下标 也可能是list的元素)
                                if (mAdapter.getSelectItems().contains(msg.arg1)) {
                                    mAdapter.getSelectItems().remove(Integer.valueOf(removedPosition));
                                }
                                ArrayList<Integer> tmps = new ArrayList<Integer>();
                                for (Integer position : mAdapter.getSelectItems()) {
                                    if (position < removedPosition) {
                                        tmps.add(position);
                                    } else if (position > removedPosition) {
                                        tmps.add(position - 1);
                                    } else {
                                        // 删除的是选中的
                                        continue;
                                    }
                                }
                                mAdapter.getSelectItems().clear();
                                mAdapter.getSelectItems().addAll(tmps);
                                mAdapter.getItems().remove(removedPosition);
                                mAdapter.notifyDataSetChanged();
                            }
                        });
                        break;
                    case 0:
                        showToast(deleteResult.getMessage());
                        break;
                }
                return true;
        }
        return super.handleMessage(msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 编辑"寄"件人
            case R.id.receiver_edit:
                ReceiverBean item = (ReceiverBean) v.getTag();
                HandlerMgr.sendMessage(MsgID.receiver_edit_history2new, item);
                break;
        }
    }
}
